package com.winning.pmph.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.winning.pmph.entity.*;
import com.winning.pmph.enumeration.KnowledgeSystem;
import com.winning.pmph.mapper.FlowChartMapper;
import com.winning.pmph.mapper.PlatformKnowledgeLibMapper;
import com.winning.pmph.utils.*;
import com.winning.pmph.vo.ReleasedFlowChartSync;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 刘亚飞
 * @Description
 * @create 2020-10-20 19:15
 */
@Component
@Transactional
@Slf4j
public class FlowChartService extends ServiceImpl<FlowChartMapper, FlowChart> {
    @Resource
    private TaskService taskService;
    @Resource
    private TaskItemService taskItemService;
    @Resource
    private ReleasedFlowChartService releasedFlowChartService;
    @Resource
    FlowChartService flowChartService;
    @Resource
    private KnowledgeSyncStatusService knowledgeSyncStatusService;
    @Resource
    private FlowChartMapper flowChartMapper;
    @Resource
    private RuleItemService ruleItemService;
    @Resource
    private PlatformKnowledgeLibMapper platformKnowledgeLibMapper;

    public boolean deleteById(String id) {
        String sql = "update flow_chart set deleted = 1 where id= '" + id + "'";
        flowChartService.getBaseMapper().executeUpdate(sql);
        return true;
    }

    public FlowChart save(FlowChart flowChart, String taskItemId, String status) {
        saveOrUpdate(flowChart);
        HistoryUtils.save(flowChart.getId(), flowChart.getFlowName(), History.OPERATE_NEW, History.OPERATE_RESULT_SUCCESS);
        String sql = "update task_item set knowledge_id = '" + flowChart.getId() + "' ,updated_time = '" + LocalDateTimeUtil.getNowAsString() + "',status = '" + status + "',name = '" + flowChart.getFlowName() + "' ";
        if (TaskItem.STATUS_COMMIT == Integer.parseInt(status)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String submitTime = dateFormat.format(new Date());
            sql += ",submit_time='" + submitTime + "'";
        }
        sql += " where id = '" + taskItemId + "' and status !=" + TaskItem.STATUS_RELEASED;
        taskItemService.getBaseMapper().executeUpdate(sql);
        return flowChart;
    }

    public int updateById(FlowChart flowChart, String taskItemId, String status, String rejectReason, String type) throws Exception {
        if (Integer.parseInt(status) == TaskItem.STATUS_COMMIT) {
            HistoryUtils.save(flowChart.getId(), flowChart.getFlowName(), History.OPERATE_COMMIT, History.OPERATE_RESULT_SUCCESS);
        } else if (Integer.parseInt(status) == TaskItem.STATUS_PASS || Integer.parseInt(status) == TaskItem.STATUS_PASS_1 || Integer.parseInt(status) == TaskItem.STATUS_PASS_2) {
            HistoryUtils.save(flowChart.getId(), flowChart.getFlowName(), History.OPERATE_PASS, History.OPERATE_RESULT_SUCCESS);
        } else if (Integer.parseInt(status) == TaskItem.STATUS_REJECT || Integer.parseInt(status) == TaskItem.STATUS_REJECT_2 || Integer.parseInt(status) == TaskItem.STATUS_REJECT_3) {
            HistoryUtils.save(flowChart.getId(), flowChart.getFlowName(), History.OPERATE_REJECT, History.OPERATE_RESULT_SUCCESS);
        }
        if (Integer.parseInt(status) != TaskItem.STATUS_RELEASED) {
            int auditLevel = flowChartAuditLevel(taskItemId);
            Integer modifiedStatus = KnowledgeEditUtil.auditStatus(flowChart.getId(), auditLevel, type);
            String sql1 = "update task_item set knowledge_id = '" + flowChart.getId() + "',updated_time = '" + LocalDateTimeUtil.getNowAsString() + "',status =" + modifiedStatus + ",name =  '" + flowChart.getFlowName() + "'";
            if (TaskItem.STATUS_COMMIT == Integer.parseInt(status)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String submitTime = dateFormat.format(new Date());
                sql1 += ",submit_time='" + submitTime + "'";
            }
            if (StringUtils.isNotBlank(rejectReason)) {
                sql1 += ",reject='" + rejectReason + "'";
            }
            sql1 += " where id = '" + taskItemId + "' and status != " + TaskItem.STATUS_RELEASED;
            taskItemService.getBaseMapper().executeUpdate(sql1);
        }
        if (Integer.parseInt(status) == TaskItem.STATUS_RELEASED) {
            HistoryUtils.save(flowChart.getId(), flowChart.getFlowName(), History.OPERATE_CORRECT, History.OPERATE_RESULT_SUCCESS);
            ReleasedFlowChart releasedFlowChart1 = releasedFlowChartService.getById(flowChart.getId());
            ReleasedFlowChart releasedFlowChart =JSON.parseObject(JSON.toJSONString(flowChart), ReleasedFlowChart.class);
            releasedFlowChart.setVersion(releasedFlowChart1.getVersion() + 1);
            releasedFlowChart.setChartJson(flowChart.getChartJson());
            releasedFlowChartService.updateById(releasedFlowChart);
            ClassPathResource templateFileResource = new ClassPathResource("public/flowChart/export-flowChart.html");
            String templateStr = new String(FileStreamUtil.inputStreamToByte(templateFileResource.getInputStream()), "utf8");
            Document template = Jsoup.parse(templateStr);
            // 生成HTML文件
            template.body().child(0).text("let showData = " + JSON.toJSONString(releasedFlowChart.getChartJson()));
            template.body().child(1).text("let fileUrl = \"" + StringUtils.substringBeforeLast(ApplicationContextUtil.getProperty("static-file.path"), "/") + "\"");

            File file = new File(ApplicationContextUtil.BASE_DOWN_FORDER + "file/flowChart/" + releasedFlowChart.getId() + ".html");
            FileUtils.writeByteArrayToFile(file, StringEscapeUtils.unescapeHtml(template.html()).getBytes());
        } else {
            flowChartService.updateById(flowChart);
        }
        return 1;
    }


    public int queryExistSameName(String flowName, String id) {
        String sql = "select id from flow_chart where flow_name = '" + flowName + " " + "'";
        if (StringUtils.isNotBlank(id)) {
            sql += " and id != '" + id + "'";
        }
        List<FlowChart> list = flowChartService.getBaseMapper().executeMultiSelect(sql);
        return list.size();
    }

    public Page<FlowChart> queryFlowChartList(FlowChart flowChart) {
        return this.getBaseMapper()
                .queryFlowChartList(new Page(flowChart.getCurrentPage(), flowChart.getPageSize()), flowChart);
    }

    public int flowChart2ReleasedFlowChart(String id, String name) {
        releasedFlowChartService.removeById(id);
        saveFlowchartToReleased(id);
        HistoryUtils.save(id, name, History.OPERATE_RELEASE, History.OPERATE_RESULT_SUCCESS);
        try {
            Document template = Jsoup.connect(ApplicationContextUtil.getProperty("static-file.path") + "flowChart/export-flowChart.html").maxBodySize(0).get();
            // 组装content内容;
            ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getById(id);
            template.body().child(0).text("let showData = " + JSON.toJSONString(releasedFlowChart.getChartJson()));
            template.body().child(1).text("let fileUrl = \"" + StringUtils.substringBeforeLast(ApplicationContextUtil.getProperty("static-file.path"), "/") + "\"");
            File file = new File(ApplicationContextUtil.BASE_DOWN_FORDER + "file/flowChart/" + id + ".html");
            FileUtils.writeByteArrayToFile(file, StringEscapeUtils.unescapeHtml(template.html()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public Page<ReleasedFlowChart> queryReleasedFlowChartList(ReleasedFlowChart releasedFlowChart) {
        List<String> knowledgeIds = null;
        if (releasedFlowChart.getIsRevised().equals(ReleasedFlowChart.NOT_REVISED) || releasedFlowChart.getIsRevised().equals(ReleasedFlowChart.REVISED)) {
            List<TaskItem> list = taskItemService.lambdaQuery()
                    .eq(TaskItem::getType, TaskItem.TYPE_EDIT)
                    .eq(TaskItem::getDeleted, TaskItem.NO_DELETED)
                    .ne(TaskItem::getStatus, TaskItem.STATUS_RELEASED).list();
            knowledgeIds = list.stream().map(TaskItem::getKnowledgeId).collect(Collectors.toList());
        }
        LambdaQueryChainWrapper<ReleasedFlowChart> wrapper = releasedFlowChartService.lambdaQuery()
                .eq(ReleasedFlowChart::getDeleted, ReleasedFlowChart.UN_DELETE)
                .like(StringUtils.isNotBlank(releasedFlowChart.getFlowName()), ReleasedFlowChart::getFlowName, releasedFlowChart.getFlowName())
                .eq(StringUtils.isNotBlank(releasedFlowChart.getCreatedBy()), ReleasedFlowChart::getCreatedBy, releasedFlowChart.getCreatedBy())
                .eq(StringUtils.isNotBlank(releasedFlowChart.getBelongingItemId()), ReleasedFlowChart::getBelongingItemId, releasedFlowChart.getBelongingItemId())
                .eq(StringUtils.isNotBlank(releasedFlowChart.getScienceTagId()), ReleasedFlowChart::getScienceTagId, releasedFlowChart.getScienceTagId())
                .eq(Objects.nonNull(releasedFlowChart.getVersion()), ReleasedFlowChart::getVersion, releasedFlowChart.getVersion())
                .in(releasedFlowChart.getIsRevised().equals(ReleasedFlowChart.NOT_REVISED), ReleasedFlowChart::getId, knowledgeIds)
                .notIn(releasedFlowChart.getIsRevised().equals(ReleasedFlowChart.REVISED), ReleasedFlowChart::getId, knowledgeIds);
        if (CollectionUtils.isNotEmpty(releasedFlowChart.getQueryCreatedTime())) {
            wrapper.between(ReleasedFlowChart::getCreatedTime, releasedFlowChart.getQueryCreatedTime().get(0),
                    releasedFlowChart.getQueryCreatedTime().get(1));
        }
        Page<ReleasedFlowChart> page = null;
        if (releasedFlowChart.getCurrentPage() != null && releasedFlowChart.getPageSize() != null) {
            page = wrapper.orderByDesc(ReleasedFlowChart::getUpdatedTime).orderByAsc(ReleasedFlowChart::getId)
                    .page(new Page<>(releasedFlowChart.getCurrentPage(), releasedFlowChart.getPageSize()));
        } else {
            page = wrapper.orderByDesc(ReleasedFlowChart::getUpdatedTime).orderByAsc(ReleasedFlowChart::getId)
                    .page(new Page<>());
        }
        return page;
    }

    public List<FlowChart> queryFlowChart(FlowChart flowChart, String createdTime) {
        String sql = "select id,\n" +
                "flow_name,\n" +
                "belonging_item_id,\n" +
                "(select name from rule_item where id = belonging_item_id) as belonging_item_name,\n" +
                "science_tag_id,\n" +
                "(select name from rule_item where id = science_tag_id) as scienceTagName,\n" +
                "chart_json,\n" +
                "(select name from user where user_name = flow_chart.created_by) as created_by,\n" +
                "created_time,reject_reason,version from flow_chart where deleted = 0 and id in(select ti.knowledge_id from task_item ti LEFT JOIN  task t on t.id=ti.task_id where ti.status='" + TaskItem.STATUS_PASS + "' and t.system_type='flowchart')";
        if (StringUtils.isNotBlank(flowChart.getFlowName())) {
            sql += " and flow_name like '%" + flowChart.getFlowName() + "%'";
        }
        if (StringUtils.isNotBlank(flowChart.getCreatedBy())) {
            sql += " and created_by in (select user_name from user where name like '%" + flowChart.getCreatedBy() + "%')";
        }
        if (StringUtils.isNotBlank(flowChart.getBelongingItemId())) {
            sql += " and belonging_item_id = '" + flowChart.getBelongingItemId() + "'";
        }
        if (StringUtils.isNotBlank(flowChart.getScienceTagId())) {
            sql += " and science_tag_id = '" + flowChart.getScienceTagId() + "'";
        }
        if (StringUtils.isNotBlank(flowChart.getId())) {
            sql += " and id = '" + flowChart.getId() + "'";
        }

        if (StringUtils.isNotBlank(createdTime)) {
            String startTime = (createdTime.split(",")[0].trim());
            String endTime = (createdTime.split(",")[1].trim());
            sql += " created_time >= '" + startTime + "' and created_time <= '" + endTime + "'";
        }
        sql += " order by updated_time desc";
        List<FlowChart> list = flowChartService.getBaseMapper().executeMultiSelect(sql);
        return list;
    }


    public void ReleasedFlowChart2FlowChart(String id) {
        ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getById(id);
        FlowChart flowChart = JSON.parseObject(JSON.toJSONString(releasedFlowChart), FlowChart.class);
        saveOrUpdate(flowChart);
    }


    public int rejectFlowChart(String id, String reject) {
        String sql = "update flow_chart set reject_reason='" + reject + "',status=3 where id='" + id + "'";
        return getBaseMapper().executeUpdate(sql);
    }


    public void multiInsertTaskItem(String taskId, String remark, String username, List<ReleasedFlowChart> releasedFlowChartList, Set<String> knowledgeInProcessIdSet) {
        for (ReleasedFlowChart flowChart : releasedFlowChartList) {
            if (!knowledgeInProcessIdSet.contains(flowChart.getId())) {
                TaskItem taskItem = new TaskItem();
                taskItem.setTaskId(taskId);
                taskItem.setKnowledgeId(flowChart.getId());
                taskItem.setName(flowChart.getFlowName());
                taskItem.setRemark(remark);
                // 查询上次关联的子任务, 字数;
                TaskItem dbTaskItem = taskItemService.getBaseMapper().selectBeanByWherePart(
                        " knowledge_id = '" + flowChart.getId() + "' " +
                                " order by updated_time limit 1");
                if (Objects.nonNull(dbTaskItem)) {
                    taskItem.setWordsCount(dbTaskItem.getWordsCount());
                }
                taskItem.setType(TaskItem.TYPE_EDIT);
                taskService.saveTaskItem(taskItem, username);
            }
        }
    }

    private void saveFlowchartToReleased(String id) {
        FlowChart flowChart = getById(id);
        ReleasedFlowChart releasedFlowChart = new ReleasedFlowChart();
        releasedFlowChart.setId(flowChart.getId());
        releasedFlowChart.setFlowName(flowChart.getFlowName());
        releasedFlowChart.setChartJson(flowChart.getChartJson());
        releasedFlowChart.setBelongingItemId(flowChart.getBelongingItemId());
        releasedFlowChart.setScienceTagId(flowChart.getScienceTagId());
        releasedFlowChart.setDeleted(flowChart.getDeleted());
        releasedFlowChart.setVersion(flowChart.getVersion() + 1);
        releasedFlowChartService.saveOrUpdate(releasedFlowChart);
        String taskSql = "update task_item set status=" + TaskItem.STATUS_RELEASED + " where knowledge_id='" + id + "'";
        taskItemService.getBaseMapper().executeUpdate(taskSql);
        flowChartService.removeById(id);

    }

    private int flowChartAuditLevel(String taskItemId) throws Exception {
        String sql = "select t.*\n" +
                "from task as t\n" +
                "         left join task_item ti on t.id = ti.task_id\n" +
                "where ti.id = '" + taskItemId + "' and t.status != " + Task.STATUS_FINISHED + " and ti.deleted = " + TaskItem.NO_DELETED;

        List<Task> taskList = taskService.getBaseMapper().executeMultiSelect(sql);
        if (taskList.size() > 1) {
            throw new Exception("一个子任务绑定了多个任务");
        } else if (taskList.size() == 1) {
            return taskList.get(0).getAuditLevel();
        } else {
            throw new Exception("子任务没有绑定任何任务");
        }
    }

    public Page<ReleasedFlowChart> querySyncList(ReleasedFlowChart releasedFlowChart) {
        Page<ReleasedFlowChart> releasedFlowChartPage = flowChartMapper.querySyncList(new Page(releasedFlowChart.getCurrentPage(), releasedFlowChart.getPageSize()),
                releasedFlowChart);
        Map<String, RuleItem> ruleItemMap = ruleItemService.lambdaQuery().in(RuleItem::getRuleId, "11", "13").list()
                .stream().collect(Collectors.toMap(RuleItem::getId, Function.identity()));
        releasedFlowChartPage.getRecords().forEach(t -> {
            t.setBelongingItemName(ruleItemMap.get(t.getBelongingItemId()).getName());
            t.setScienceTagName(ruleItemMap.get(t.getScienceTagId()).getName());
        });
        return releasedFlowChartPage;
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void syncToPlatform(ReleasedFlowChart releasedFlowChart, String userName, String operation) {
        // 当前列表数据全部推送
        List<ReleasedFlowChart> list = Lists.newArrayList();
        // 当前列表数据全部推送
        if (StringUtils.isBlank(releasedFlowChart.getSyncIds())) {
            list = releasedFlowChartService.lambdaQuery().eq(ReleasedFlowChart::getDeleted, Const.DELETED_NO)
                    .like(StringUtils.isNotBlank(releasedFlowChart.getFlowName()), ReleasedFlowChart::getFlowName, releasedFlowChart.getFlowName())
                    .like(StringUtils.isNotBlank(releasedFlowChart.getScienceTagId()), ReleasedFlowChart::getScienceTagId, releasedFlowChart.getScienceTagId())
                    .like(StringUtils.isNotBlank(releasedFlowChart.getBelongingItemId()), ReleasedFlowChart::getBelongingItemId, releasedFlowChart.getBelongingItemId())
                    .list();
        } else {
            // 页面选中的推送
            list = releasedFlowChartService.lambdaQuery().in(ReleasedFlowChart::getId, releasedFlowChart.getSyncIds().split(",")).list();
        }
        syncData(list, releasedFlowChart.getSelectedPlatform(), userName, operation);
    }

    /**
     * 推送除推送成功之外的数据
     *
     * @param platformId
     * @param userName
     * @param operation
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void syncWaitAndFailedToPlatform(String platformId, String userName, String operation) {
        // 删除除推送成功外的数据
        knowledgeSyncStatusService.remove(Wrappers.lambdaQuery(KnowledgeSyncStatus.class)
                .eq(KnowledgeSyncStatus::getKnowledgeLibId, KnowledgeLib.FLOW_CHART_LIB_ID)
                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                .ne(KnowledgeSyncStatus::getKind, KnowledgeSyncStatus.KIND_SUCCESS));
        // 查询出推送成功的
        List<KnowledgeSyncStatus> successList = knowledgeSyncStatusService.lambdaQuery()
                .eq(KnowledgeSyncStatus::getKnowledgeLibId, KnowledgeLib.FLOW_CHART_LIB_ID)
                .eq(KnowledgeSyncStatus::getPlatformId, platformId)
                .list();
        List<ReleasedFlowChart> list = releasedFlowChartService.lambdaQuery().eq(ReleasedFlowChart::getDeleted, Const.DELETED_NO).list();
        if (CollectionUtils.isNotEmpty(successList)) {
            List<String> successIdList = successList.stream()
                    .map(KnowledgeSyncStatus::getKnowledgeId).collect(Collectors.toList());
            // 过滤掉推送成功的, 推送未发送,推送失败,消费失败的数据
            list = list.stream().filter(t -> !successIdList.contains(t.getId())).collect(Collectors.toList());
        }
        syncData(list, platformId, userName, operation);
    }

    private void syncData(List<ReleasedFlowChart> list, String selectedPlatform, String userName, String operation) {
        log.info("流程图推送开始");
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有待推送的流程图");
            return;
        }
        // 组装待推送数据
        Map<String, RuleItem> ruleItemMap = ruleItemService.lambdaQuery().in(RuleItem::getRuleId, "11", "13").list()
                .stream().collect(Collectors.toMap(RuleItem::getId, Function.identity()));
        list.forEach(t -> {
            t.setScienceTagName(ruleItemMap.get(t.getScienceTagId()).getName());
            t.setBelongingItemName(ruleItemMap.get(t.getBelongingItemId()).getName());
        });
        List<ReleasedFlowChartSync> syncList = JSON.parseArray(JSON.toJSONString(list), ReleasedFlowChartSync.class);
        // 推送
        Map<String, String> syncDataMap = Maps.newHashMap();
        syncDataMap.put("syncPlatform", selectedPlatform);
        syncDataMap.put("userName", userName);
        syncDataMap.put("knowledgeLibId", KnowledgeLib.FLOW_CHART_LIB_ID);
        syncList.forEach(syncItem -> {
            syncItem.setHtmlPath("/pmph/action/file/getFile?filename=file/flowChart/" + syncItem.getId() + ".html");
            JSONObject object = new JSONObject();
            object.put("type", KnowledgeSystem.FLOWCHART.value);
            object.put("option", operation);
            object.put("data", syncItem);
            boolean sendFlag = RocketMQProducerUtil.sendMessage(selectedPlatform,
                    KnowledgeSystem.FLOWCHART.value, syncItem.getFlowName(),
                    JSON.toJSONString(object));
            // 记录同步日志
            syncDataMap.put("knowledgeId", syncItem.getId());
            knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag);
        });
        log.info("推送流程图结束");
    }

    public void ReleasedFlowChartDeleteById(String id, String status) {
        if (StringUtils.equals(status, "published")) {
            ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getById(id);
            releasedFlowChart.setVersion(releasedFlowChart.getVersion() + 1);
            releasedFlowChart.setDeleted(ReleasedMedicalCalculator.DELETED_YES);
            // 修改知流程图
            releasedFlowChartService.updateById(releasedFlowChart);
            HistoryUtils.save(id, releasedFlowChart.getFlowName(), History.OPERATE_DELETE, History.OPERATE_RESULT_SUCCESS);
            // 同步逻辑删除子任务,如果该知识有修订的,不允许删除,所以不加status = 8 的判断
            LambdaUpdateWrapper<TaskItem> taskItemUpdateWrapper = Wrappers.lambdaUpdate();
            taskItemUpdateWrapper.set(TaskItem::getDeleted, TaskItem.DELETED);
            taskItemUpdateWrapper.eq(TaskItem::getKnowledgeId, id);
            taskItemService.update(taskItemUpdateWrapper);

            knowledgeSyncStatusService.getBaseMapper().executeUpdate("update knowledge_sync_status set kind = " + KnowledgeSyncStatus.FAILED_KIND_WAITING + " where knowledge_id = '" + id + "'");
            List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.lambdaQuery().eq(PlatformKnowledgeLib::getKnowledgeLibId, KnowledgeLib.FLOW_CHART_LIB_ID).list();
            platformKnowledgeLibs.forEach(t -> {
                syncWaitAndFailedToPlatform(t.getPlatformId(), PMPHAppUtil.getCurrentUserEnName(), Const.SYNC_OPERATION_DELETE);
            });
        }
    }

    public void ReleasedFlowChartRecover(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            // 修改发布医学计算器 delete version
            ReleasedFlowChart releasedFlowChart = releasedFlowChartService.getById(id);
            releasedFlowChart.setDeleted(ReleasedKnowledge.DELETED_NO);
            releasedFlowChart.setVersion(releasedFlowChart.getVersion() + 1);
            releasedFlowChartService.updateById(releasedFlowChart);
            HistoryUtils.save(id, releasedFlowChart.getFlowName(), History.OPERATE_RECOVER, History.OPERATE_RESULT_SUCCESS);
            // 恢复子任务
            taskItemService.getBaseMapper().executeUpdate("update task_item set deleted = " + TaskItem.NO_DELETED + ", updated_time='" + LocalDateTimeUtil.getNowAsString() + "' where knowledge_id = '" + id + "'");
            //修改同步状态
            knowledgeSyncStatusService.getBaseMapper().executeUpdate("update knowledge_sync_status set kind = " + KnowledgeSyncStatus.FAILED_KIND_WAITING + " where knowledge_id = '" + id + "'");
            List<PlatformKnowledgeLib> platformKnowledgeLibs = platformKnowledgeLibMapper.lambdaQuery().eq(PlatformKnowledgeLib::getKnowledgeLibId, KnowledgeLib.FLOW_CHART_LIB_ID).list();
            platformKnowledgeLibs.forEach(t -> {
                syncWaitAndFailedToPlatform(t.getPlatformId(), PMPHAppUtil.getCurrentUserEnName(), Const.SYNC_OPERATION_ADD);
            });
        }
    }

    public void deleteReleasedFlowChart(String id, String name, String updatedTime, String updatedBy, String operationType) {
        if ("all".equals(operationType)) {
            LambdaQueryWrapper<ReleasedFlowChart> query = Wrappers.lambdaQuery(ReleasedFlowChart.class)
                    .like(StringUtils.isNoneBlank(name), ReleasedFlowChart::getFlowName, name)
                    .eq(ReleasedFlowChart::getDeleted, Const.DELETED_YES)
                    .eq(StringUtils.isNoneBlank(updatedBy), ReleasedFlowChart::getUpdatedBy, updatedBy);
            if (StringUtils.isNotEmpty(updatedTime)) {
                query = query.ge(ReleasedFlowChart::getUpdatedTime, updatedTime.split(",")[0].trim())
                        .le(ReleasedFlowChart::getUpdatedTime, updatedTime.split(",")[1].trim());
            }
            List<ReleasedFlowChart> records = releasedFlowChartService.page(new Page<>(), query).getRecords();
            if (CollectionUtils.isNotEmpty(records)) {
                List<String> releasedMedicalCalculatorIds = records.stream().map(ReleasedFlowChart::getId).collect(Collectors.toList());
                taskItemService.remove(Wrappers.lambdaQuery(TaskItem.class).in(TaskItem::getKnowledgeId, releasedMedicalCalculatorIds));
                releasedFlowChartService.removeByIds(releasedMedicalCalculatorIds);
            }
        } else {
            taskItemService.remove(Wrappers.lambdaQuery(TaskItem.class).eq(TaskItem::getKnowledgeId, id));
            releasedFlowChartService.removeById(id);
        }
    }
}
